<template>
    <div class="login-container">
        <div class="chat-list">
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>消息列表</span>
                </div>
                <div v-if="chatUserList" v-for="(item,key) in chatUserList" @click="goToChat(item,key)" class="user-list-wrapper" :class='key==choiceIndex?"active":""'>
                    <el-badge v-if="haveMsg[item.u_id]" :value="haveMsg[item.u_id]" :max="99" class="item">
                        <img :src="item.avatar" class="user-list-avatar">
                    </el-badge>
                    <img v-else :src="item.avatar" class="user-list-avatar">
                    <div class="user-list-name">
                        <div>{{item.nickName}}</div>
                        <div class="last-content">
                            {{lastContentArr[item.u_id].msg==1?lastContentArr[item.u_id].message:lastContentArr[item.u_id].image==1?'[图片]':'[订单列表]'}}
                        </div>

                    </div>
                </div>
                <div v-else class="no-chat-user">暂时还没有聊天消息!</div>
            </el-card>
        </div>
        <div class="chat-content">
            <div class="content-header">
                {{choiceUser.nickName}}
            </div>
            <div v-if="choiceIndex!=-1">
                <div class='content-container' id="chatContainer">
                    <div v-for="(item,index) in chatContent"  >
                        <div class='chatTime' v-if="item['time']">{{item['time']}}</div>
                        <div class='self-wrapper' v-if='item["sid"]==seller.id && item["msg"]==1'>
                            <img :src='item["avatar"]' class='self-avatar'>
                            <div class="self-text-wrapper-icon"></div>
                            <div class='self-text-wrapper'>
                                <div class='self-text'>{{item['message']}}</div>
                            </div>
                            <div class='clr'></div>
                        </div>
                        <div class='self-wrapper' v-if='item["image"]==1&&item["sid"]==seller.id'>
                            <img :src='item["avatar"]' class='self-avatar'>
                            <div class="avatar-wrapper-icon"></div>
                            <div class='self-img-wrapper'>
                                <img class='chat-img' :src='item["url"]'>
                            </div>
                            <div class='clr'></div>
                        </div>
                        <div class='self-order-wrapper' v-if='item["order"]==1&&item["sid"]==seller.id'>
                            <img :src='item["avatar"]' class='self-avatar'>
                            <div class="avatar-wrapper-icon"></div>
                            <div class='self-order-text-wrapper'>
                                <div class='self-text'>
                                    <div class='order-title-wrapper'>订单编号:{{item["order_id"]}}</div>
                                    <div class='order-item-wrapper' v-for='(orderItem,index) in item["orders"]'>
                                        <img class='chat-order-icon' :src="orderItem.icon">
                                        <div class='chat-order-title'>{{orderItem.name}}</div>
                                    </div>
                                </div>
                            </div>
                            <div class='clr'></div>
                        </div>

                        <div class='other-wrapper' v-if='item["uid"]==choiceUser.u_id && item["msg"]==1'>
                            <div class="other-text-wrapper-icon"></div>
                            <div class='other-text-wrapper'>
                                <div class='self-text'>{{item['message']}}</div>
                            </div>
                            <img :src='item["avatar"]' class='other-avatar'>
                        </div>
                        <div class='other-wrapper' v-if='item["uid"]==choiceUser.u_id && item["image"]==1'>
                            <div class="other-text-wrapper-icon"></div>
                            <div class='other-img-wrapper'>
                                <img class='chat-img' :src='item["url"]'>
                            </div>
                            <img :src='item["avatar"]' class='other-avatar'>
                        </div>
                        <div class='self-order-wrapper' v-if='item["order"]==1&&item["uid"]==choiceUser.u_id'>
                            <img :src='item["avatar"]' class='other-avatar'>
                            <div class="other-text-wrapper-icon"></div>
                            <div class='other-order-text-wrapper'>
                                <div class='self-text'>
                                    <div class='order-title-wrapper'>订单编号:{{item["order_id"]}}</div>
                                    <div class='order-item-wrapper' v-for='(orderItem,index) in item["orders"]'>
                                        <img class='chat-order-icon' :src="orderItem.icon">
                                        <div class='chat-order-title'>{{orderItem.name}}</div>
                                    </div>
                                </div>
                            </div>
                            <div class='clr'></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="content-bottom" v-if="choiceIndex!=-1">
                <div class="media-wrapper">
                    <el-button class="order-button" type="primary" @click="getOrderList">订单</el-button>
                    <el-upload class="upload-demo" :multiple="multiple" action="http://www.jiatingyigou.com:7001/upload/img" :before-upload="beforeCoverUpload"
                        :on-remove="handleRemove" list-type="picture" :on-success="handleCoverSuccess" ref="upload">
                        <el-button size="small" type="primary">图片</el-button>
                        <div slot="tip" class="el-upload__tip">只能发送jpg/png文件，且不超过2m</div>
                        </el-upload>

                </div>
                <el-input class="input-wrapper" type="textarea" :rows="4" placeholder="请输入内容" v-model="message">
                </el-input>
                <el-button class="send-buttom" type="success" @click="sendMessage">发送</el-button>

            </div>
        </div>
        <el-dialog title="订单列表" :visible.sync="dialogVisible" width="90%" :before-close="handleClose">
            <el-table :data="orderList" style="width: 100%">
                <el-table-column prop="seller_name" label="商家名称" width="140">
                </el-table-column>
                <el-table-column prop="orderTime" label="下单时间" width="140">
                </el-table-column>
                <el-table-column prop="count" label="商品数量" width="100">
                </el-table-column>
                <el-table-column prop="sumPrice" label="总价" width="100">
                </el-table-column>
                <el-table-column label="订单状态" width="100">
                    <template scope="scope">
                        <el-icon name="status"></el-icon>
                        <el-tag :type="orderStatus(scope.row.status).btn">{{ orderStatus(scope.row.status).text }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template scope="scope">
                        <el-button size="small" type="info" @click="sendOrder(scope.row.order_id)">发送该订单</el-button>
                    </template>
                </el-table-column>
            </el-table>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    import { getSellerInfo, getUserInfo } from '@/api/seller'
    import formatDate from "@/utils/date";
    import { getUserOrder, getOrderDetail } from '@/api/order'
    import { getToken, setNewMsg, getNewMsg } from '@/utils/auth'
    import * as wilddog from 'wilddog'
    var config = {
        syncURL: "https://wd5887692246axvric.wilddogio.com" //输入节点 URL
    };
    wilddog.initializeApp(config);
    export default {
        name: 'chat',
        data() {
            return {
                multiple: false,
                imageUrl: '',
                message: "",
                seller: {},
                chatContent: [],
                chatUserList: {},
                user: {},
                choiceUser: {
                    nickName: "",
                    id: 0,
                    u_id: "",
                },
                dialogVisible: false,
                orderList: [],
                choiceIndex: -1,
                haveMsg: {},
                flag: false,
                sumMsg: 0,
                count: {},
                beforeCount: {},
                keyList: [],
                allChatContent: {},
                lastContentArr: {}
            }
        },
        watch: {
            chatContent() {
                this.$nextTick(() => {
                    var container2 = this.$el.querySelector("#chatContainer");
                    container2.scrollTop =container2.scrollHeight
                })
            }
        },
        created() {
            let id = getToken()
            var that = this
            this.$nextTick(() => {
                var getChoiceUser = this.choiceUser
                getSellerInfo(id).then((res) => {

                    if (res.message == "ok") {

                        this.seller = res.seller

                        var sid = this.seller.id

                        var ref = wilddog.sync().ref().orderByPriority().limitToLast(500);

                        ref.on("child_added", function (snapshot) {
                            var key = snapshot.key()
                            var node = `chat-with-${sid}-`
                            var keyArr = key.split(node)
                            var uid = keyArr[1]
                            console.log("888", key.indexOf(node) == 0, !that.chatUserList[uid], key)
                            if (key.indexOf(node) == 0 && !that.chatUserList[uid]) {
                                var item = { "key": key, "uid": uid }
                                var chatListUser = wilddog.sync().ref(item.key).orderByPriority().limitToLast(500);
                                chatListUser.on("value", function (UserContentList) {

                                    var chatContents = UserContentList.val()

                                    that.$set(that.allChatContent, item.uid, chatContents)
                                    var count = 0
                                    var lastContent = ""
                                    for (var keyItem in chatContents) {
                                        if (!chatContents[keyItem].time) {
                                            count++
                                        }
                                        lastContent = chatContents[keyItem]
                                    }

                                    var localBeforeCount = getNewMsg()

                                    var uid = item.uid
                                    var beforeCountId = uid + sid
                                    that.$set(that.lastContentArr, uid, lastContent)
                                    that.$set(that.count, uid, count)
                                    if (localBeforeCount && localBeforeCount[beforeCountId]) {
                                        var newCount = count - localBeforeCount[beforeCountId]
                                        if (getChoiceUser && getChoiceUser.u_id == uid) {
                                            console.log("22", getChoiceUser.u_id, uid, count)
                                            var chatArr = []
                                            for (let key in chatContents) {
                                                chatArr.push(chatContents[key])
                                            }
                                            that.chatContent = chatArr
                                            that.$set(that.beforeCount, beforeCountId, count)
                                            setNewMsg(that.beforeCount)
                                        } else {

                                            that.$set(that.haveMsg, uid, newCount)
                                            that.$set(that.beforeCount, beforeCountId, localBeforeCount[beforeCountId])

                                        }

                                    } else {
                                        if (getChoiceUser && getChoiceUser.u_id == uid) {
                                            that.$set(that.beforeCount, beforeCountId, count)
                                            setNewMsg(that.beforeCount)
                                        } else {

                                            that.$set(that.haveMsg, uid, count)
                                        }
                                    }
                                })

                                getUserInfo(uid).then((res) => {
                                    console.log("222999")
                                    if (res.message == "ok") {
                                        that.user = res.user
                                        that.user
                                        let uid = that.user.u_id

                                        that.$set(that.chatUserList, uid, that.user)
                                    }
                                })
                            }
                        })

                    }

                })


            })


        },
        beforeDestroy() {
            this.choiceUser.nickName = ""
            this.choiceUser.id = 0
            this.choiceUser.u_id = ""

        },
        methods: {
            sendOrder(order_id) {
                var sid = this.seller.id
                var avatar = this.seller.avatar
                var user = this.choiceUser
                var beforeCountId = user.u_id + sid
                this.count[user.u_id] = this.count[user.u_id] + 1
                this.beforeCount[beforeCountId] = this.count[user.u_id]
                setNewMsg(this.beforeCount)
                getOrderDetail(order_id).then((res) => {
                    if (res.message == "ok") {
                        var orderDetail = res.orders
                        orderDetail = orderDetail.map(({ name, icon }) => {
                            return { name, icon }
                        })
                        this.flag = false
                        wilddog.sync().ref(`chat-with-${sid}-${user.u_id}`).push({ "order": 1, "order_id": order_id, "avatar": avatar, "orders": orderDetail, "uid": -1, "sid": sid });
                        this.dialogVisible = false
                    }
                })
            },
            getOrderList() {
                this.dialogVisible = true
                var id = this.choiceUser.id

                getUserOrder(id).then((res) => {
                    if (res.status == 1) {
                        this.orderList = res.orders
                        this.orderList.map(item => {
                            item.orderTime = formatDate(
                                new Date(item.orderTime * 1),
                                "yy-MM-dd hh:mm"
                            );
                            return item;
                        });
                    }
                })

            },
            handleCoverSuccess(res, file) {
                this.avator = URL.createObjectURL(file.raw);
                this.imageUrl = "http://" + res.data.url;
                this.$message({
                    message: '上传成功',
                    type: 'success'
                });
            },
            beforeCoverUpload(file) {
                this.$message('正在上传...');
                const isJPG = file.type === "image/jpeg";
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error("上传头像图片只能是 JPG 格式!");
                }
                if (!isLt2M) {
                    this.$message.error("上传头像图片大小不能超过 2MB!");
                }
                return isJPG && isLt2M;
            },
            handleRemove(file, fileList) {
                this.imageUrl = ""
            },
            handlePictureCardPrediv(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            handleSuccess(res, file, fileList) {
                var newImg = {
                    sell_id: this.form.id,
                    uid: file.raw.uid,
                    status: "success",
                    url: "http://" + res.data.url,
                }
                addSellerImg(newImg).then((response) => {
                    if (response.id) {
                        newImg.id = response.id
                        this.$message({
                            type: "success",
                            message: "添加新图片成功!"
                        });
                    }
                })
                this.form.pics.push(newImg)
                this.imgList.concat(newImg)
            },
            goToChat(user, index) {
                this.choiceUser.id = user.id,
                    this.choiceUser.u_id = user.u_id,
                    this.choiceUser.nickName = user.nickName
                console.log(this.choiceUser)

                this.choiceIndex = index
                var sid = this.seller.id
                this.haveMsg[user.u_id] = 0
                var beforeCountId = user.u_id + sid
                this.beforeCount[beforeCountId] = this.count[user.u_id]
                setNewMsg(this.beforeCount)
                var chatArr = []
                var dataList = this.allChatContent[user.u_id]
                for (var key in dataList) {
                    chatArr.push(dataList[key])
                }
                this.chatContent = chatArr

            },
            sendMessage() {
                var sid = this.seller.id
                var avatar = this.seller.avatar
                var user = this.choiceUser
                var message = this.message.trim()
                var img = this.imageUrl
                var key = `chat-with-${sid}-${user.u_id}`
                this.count[user.u_id] = this.count[user.u_id] + 1
                var beforeCountId = user.u_id + sid
                this.beforeCount[beforeCountId] = this.count[user.u_id]
                setNewMsg(this.beforeCount)
                if (message == '' && img == '') {
                    return
                }
                if (message != '') {

                    wilddog.sync().ref(`chat-with-${sid}-${user.u_id}`).push({ "message": message, "avatar": avatar, "uid": -1, "sid": sid, "msg": 1 })

                    this.message = ""
                }

                if (img != '') {

                    wilddog.sync().ref(`chat-with-${sid}-${user.u_id}`).push({ "image": 1, "avatar": avatar, "url": img, "uid": -1, "sid": sid, "image": 1 });
                    this.imageUrl = ""
                    this.$refs.upload.clearFiles();
                }


            },
            handleClose() {
                this.dialogVisible = false
            }, orderStatus(v) {
                switch (v) {
                    case 0:
                        return {
                            text: "待支付",
                            btn: "gray"
                        };
                        break;
                    case 1:
                        return {
                            text: "已付款，等待处理",
                            btn: "warning"
                        };
                        break;
                    case 2:
                        return {
                            text: "商品正在配送中",
                            btn: "primary"
                        };
                        break;
                    case 3:
                        return {
                            text: "交易成功，等待评价",
                            btn: "success"
                        };
                        break;
                    case 5:
                        return {
                            text: "交易关闭",
                            btn: "danger"
                        };
                        break;
                    case 4:
                        return {
                            text: "售后处理中",
                            btn: "danger"
                        };
                        break;
                }
            }
        }
    }

</script>

<style>
    .login-container {
        position: relative;
        display: flex;
        width: 80%;
        height: 750px;
    }
    
    .chat-list {
        flex: 0 0 250px;
        background: #eee;
        overflow-y: scroll
    }
    
    .chat-content {
        position: relative;
        flex: auto;
        background: white;
        height: 100%;
        border-right: 1px solid #eee;
        border-bottom: 1px solid #eee;
    }
    
    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    
    .clearfix:after {
        clear: both
    }
    
    .input-wrapper {
        position: relative;
        margin-top: -28px;
        z-index: 1;
        padding: 0 10px;
    }
    
    .box-card {
        width: 300px;
        background: #eee;
        height: 100%;
    }
    
    .content-header {
        position: relative;
        height: 57px;
        font-size: 16px;
        padding-left: 30px;
        line-height: 57px;
        border-bottom: 1px solid #eee;
    }
    
    .content-bottom {
        position: absolute;
        width: 100%;
        left: 0;
        bottom: 0;
        height: 250px;
        border-top: 1px solid #eee;
    }
    
    .media-wrapper {
        width: 100%;
        position: relative;
        height: 100px;
        padding: 5px 10px;
    }
    
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 80px;
        height: 80px;
        line-height: 80px;
        text-align: center;
    }
    
    .upload-demo {
        position: relative;
        z-index: 10;
        margin-top: 10px;
    }
    
    .avatar {
        width: 80px;
        height: 80px;
        display: block;
    }
    
    .last-content {
        position: relative;
        font-size: 12px;
        margin-top: 3px;
        color: gray;
        width: 150px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    .send-buttom {
        position: absolute;
        bottom: 20px;
        right: 20px;
    }
    
    ::-webkit-scrollbar {
        width: 0;
        height: 0;
        color: transparent;
    }
    
    .chat-wrapper {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 999;
    }
    
    .submit-container .submit-handle {
        position: relative;
        width: 140px;
        font-size: 30px;
        margin: 0 0 0 15px;
        background: #ff8c00;
        color: white;
        border-radius: 6px;
    }
    
    .content-container {
        position: relative;
        padding: 8px;
        height: 440px;
        overflow: auto;
        bottom: 0
    }
    
    .self-wrapper {
        margin: 20px 10px 30px 10px;
        position: relative;
    }
    
    .self-order-wrapper {
        margin: 20px 10px 30px 10px;
        position: relative;
    }
    
    .self-text-wrapper {
        position: relative;
        float: right;
        margin-right: 13px;
        background: greenyellow;
        max-width: 50%;
        padding: 8px;
        font-size: 15px;
        border-radius: 5px;
        z-index: 200;
        box-shadow: 1px 1px 10px solid green;
    }
    
    .self-avatar {
        position: relative;
        float: right;
        width: 40px;
        height: 40px;
        border-radius: 2px;
    }
    
    .clr {
        position: relative;
        width: 0;
        height: 0;
        clear: both;
    }
    
    .self-text-wrapper-icon {
        position: absolute;
        content: "";
        right: 50px;
        top: 10px;
        width: 10px;
        height: 10px;
        background: greenyellow;
        transform: rotate(45deg);
        z-index: 10;
        box-shadow: 1px 1px 10px solid green;
    }
    
    .avatar-wrapper-icon {
        position: absolute;
        content: "";
        right: 50px;
        top: 10px;
        width: 10px;
        height: 10px;
        background: greenyellow;
        transform: rotate(45deg);
        z-index: 10;
        box-shadow: 1px 1px 10px solid green;
    }
    
    .self-img-wrapper {
        position: relative;
        float: right;
        margin-right: 13px;
        max-width: 50%;
        border-radius: 5px;
        background: white;
        border: 1px solid greenyellow;
        z-index: 20;
    }
    
    .other-img-wrapper {
        position: relative;
        display: inline-block;
        margin-left: 4px;
        max-width: 50%;
        border-radius: 5px;
        border: 1px solid #eee;
        z-index: 20;
        background: white;
    }
    
    .self-order-text-wrapper {
        position: relative;
        float: right;
        margin-right: 13px;
        background: white;
        max-width: 50%;
        padding: 13px;
        font-size: 15px;
        border-radius: 5px;
        border: 1px solid greenyellow;
        z-index: 20;
    }
    
    .other-order-text-wrapper {
        position: relative;
        display: inline-block;
        margin-left: 6px;
        background: white;
        max-width: 50%;
        padding: 13px;
        font-size: 15px;
        border-radius: 5px;
        border: 1px solid #eee;
        z-index: 20;
    }
    
    .order-item-wrapper:last-child {
        border: none;
    }
    
    .order-title-wrapper {
        position: relative;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    .self-text {
        white-space: normal;
        overflow-wrap: break-word;
    }
    
    .other-wrapper {
        margin: 20px 10px 30px 10px;
        position: relative;
    }
    
    .other-avatar {
        position: relative;
        float: left;
        margin-right: 10px;
        width: 40px;
        height: 40px;
        border-radius: 2px;
    }
    
    .no-chat-user {
        position: relative;
        height: 30px;
        line-height: 30px;
        font-size: 14px;
        margin-left: 15px;
    }
    
    .other-text-wrapper {
        display: inline-block;
        position: relative;
        background: #eee;
        max-width: 50%;
        padding: 8px;
        font-size: 15px;
        border-radius: 5px;
        box-shadow: 1px 1px 10px solid rgba(0, 0, 0, 0.2);
        z-index: 20;
        margin-left: 4px;
    }
    
    .other-text-wrapper-icon {
        position: absolute;
        content: "";
        left: 52px;
        top: 10px;
        width: 10px;
        height: 10px;
        background: #eee;
        transform: rotate(45deg);
        z-index: 10;
    }
    
    .self-text {
        font-size: 16px;
        line-height: 25px;
        white-space: normal;
        overflow-wrap: break-word;
    }
    
    .chatTime {
        position: relative;
        font-size: 13px;
        text-align: center;
        line-height: 16px;
    }
    
    .chat-order-icon {
        display: inline-block;
        position: relative;
        width: 40px;
        height: 40px;
        padding: 8px 4px 5px 5px;
        vertical-align: top;
    }
    
    .chat-order-title {
        font-size: 13px;
        display: inline-block;
        position: relative;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding: 0 4px;
    }
    
    .chat-img {
        position: relative;
        display: block;
        width: 100px;
        height: auto;
        z-index: 20;
    }
    
    .user-list-wrapper {
        position: relative;
        display: flex;
        height: 100%;
        margin-bottom: 8px;
        font-size: 14px;
    }
    
    .user-list-wrapper::after {
        position: absolute;
        content: "";
        width: 100%;
        bottom: 0;
        left: 0;
        border-top: 1px solid rgba(0, 0, 0, 0.1)
    }
    
    .user-list-wrapper.active {
        background: rgba(0, 0, 0, 0.2);
    }
    
    .el-card__body {
        padding: 0;
    }
    
    .user-list-avatar {
        flex: 0 0 40px;
        height: 40px;
        border-radius: 6px;
        margin-top: 10px;
        margin-left: 10px;
        margin-bottom: 5px;
    }
    
    .user-list-name {
        flex: auto;
        font-size: 14px;
        margin-left: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding-top: 12px;
    }
    
    .order-button {
        margin-top: 10px;
        position: absolute;
        margin-left: 60px;
        z-index: 999;
        font-size: 12px;
        padding: 7px 10px;
    }
</style>